use common::error::MyError;
use entity::accounts;
use model::accounts::{AccountsPage, CreateAccounts, RechargeBondsModel, ResetPasswordModel};
use model::auth::LoginModel;
use security::ctx::save_token_auth;
use security::state::TokenAuthModel;

use crate::base::BaseService;
use crate::manager::accounts::AccountsManager;
use crate::manager::cash_cera::CachCeraManager;
use crate::manager::cash_cera_point::CachCeraPointManager;
use crate::manager::charac_view::CharacViewManager;
use crate::manager::limit_create_character::LimitCreateCharacterManager;
use crate::manager::member_dungeon::MemberDungeonManager;

pub struct AccountsService {}

impl
BaseService<
    i32,
    accounts::Model,
    AccountsPage,
    CreateAccounts,
    accounts::Model,
    AccountsManager,
> for AccountsService
{}

impl AccountsService {
    pub async fn reset_password(form: ResetPasswordModel) -> Result<bool, MyError> {
        AccountsManager::reset_password(form).await
    }
    pub async fn recharge_bonds(form: RechargeBondsModel) -> Result<bool, MyError> {
        if form.recharge_type == 1 {
            CachCeraManager::recharge_bonds(form).await?;
        } else {
            CachCeraPointManager::recharge_bonds(form).await?;
        }
        Ok(true)
    }

    pub async fn reset_create_role(uid: u32) -> Result<bool, MyError> {
        LimitCreateCharacterManager::reset_create_role(uid).await
    }

    pub async fn set_max_role(uid: u32) -> Result<bool, MyError> {
        CharacViewManager::set_max_role(uid).await
    }

    pub async fn open_dungeon(uid: u32) -> Result<bool, MyError> {
        MemberDungeonManager::open_dungeon(uid).await
    }

    pub async fn account_login(form: LoginModel) -> Result<String, MyError> {
        let account = AccountsManager::get_by_username(form.username.unwrap()).await?;
        match account {
            None => {
                return Err(MyError::ServerError("账号不存在或密码错误".to_string()));
            }
            Some(account) => {
                let db_password = account.password.unwrap();
                let form_password = format!("{:?}",md5::compute(form.password.unwrap()));
                if db_password == form_password {
                    return Err(MyError::ServerError("账号不存在或密码错误".to_string()));
                }else {
                    let token_auth: TokenAuthModel = crate::auth_service::build_token_auth(account.uid as i64).await?;
                    Ok(save_token_auth(account.uid as i64, account.accountname.unwrap(), token_auth)?)
                }
            }
        }
    }
}